package com.zimmur.app.mocolink.background.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zimmur.app.mocolink.background.common.PropertiesCommon;
import com.zimmur.app.mocolink.background.common.ReturnJsonEntity;
import com.zimmur.app.mocolink.background.common.StatusCodeEnum;
import com.zimmur.app.mocolink.background.util.PublicKeyUtil;
import com.zimmur.app.mocolink.background.util.SecretUtil;
import com.zimmur.app.mocolink.background.util.WanYiNoteUtil;
import com.zimmur.app.mocolink.domain.model.AppUser;
import com.zimmur.app.mocolink.domain.model.UserGrade;
import com.zimmur.app.mocolink.domain.model.VerifyMobileLog;
import com.zimmur.app.mocolink.domain.util.DateUtils;
import com.zimmur.app.mocolink.domain.util.FunctionUtil;
import com.zimmur.app.mocolink.domain.util.StringUtils;
import com.zimmur.app.mocolink.domain.vo.AppUserInfo;
import com.zimmur.app.mocolink.service.IAppUserService;
import com.zimmur.app.mocolink.service.IUserGradeService;
import com.zimmur.app.mocolink.service.IVerifyMobileService;

@RestController
@RequestMapping("/restful/user")
public class AppUserController extends BaseController {

	@Autowired
	private IAppUserService appUserService;
	@Autowired
	private IVerifyMobileService verifyMobileService;
	@Autowired
	private PublicKeyUtil publicKeyUtil;
	@Autowired
	private IUserGradeService userGradeService;
	@RequestMapping("/sendNote")
	public ReturnJsonEntity sendNote(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum codeEnum = StatusCodeEnum.CODE100000;
		String mobileNo = getParam("mobileNo");
		Integer type = getParam("type", 1);
		if(FunctionUtil.isMobile(mobileNo)){
			String code = WanYiNoteUtil.sendNote(mobileNo, type);
			if(WanYiNoteUtil.SendTooMoreError.equals(code)){
				codeEnum=StatusCodeEnum.CODE202401;
				entity.setMsg(codeEnum.getMsg());
			}else if(WanYiNoteUtil.UnknowError.equals(code)){
				codeEnum=StatusCodeEnum.CODE100000;
				entity.setMsg("系统繁忙，请稍后再试");
			}else{
				verifyMobileService.addMobileLog(mobileNo, code);
				
				codeEnum=StatusCodeEnum.CODE000000;
				entity.setMsg("验证码发送成功，请注意查收");
			}
		}else{
			codeEnum=StatusCodeEnum.CODE202402;
			entity.setMsg(codeEnum.getMsg());
		}
		entity.setCode(codeEnum.getCode());
		return entity;
	}
	@RequestMapping("/modifypassword")
	public ReturnJsonEntity modifypassword(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum codeEnum = StatusCodeEnum.CODE100000;
		String mobileNo = getParam("mobileNo");
		String password = getParam("newUserPwd");
		String verifyCode = getParam("verifyCode");
		AppUser appUser = appUserService.selectByAccount(mobileNo);
		VerifyMobileLog mobileLog = verifyMobileService.getInfoByMobile(mobileNo);
		if(appUser==null){
			codeEnum = StatusCodeEnum.CODE203401;
		}else if(mobileLog == null || !verifyCode.equals(mobileLog.getVerifyCode())){
			codeEnum = StatusCodeEnum.CODE203402;
		}else{
			appUser.setPassword(password.toUpperCase());
			appUserService.update(appUser);
			verifyMobileService.updateInfoStatus(mobileLog);
			codeEnum = StatusCodeEnum.CODE000000;
		}
		entity.init(codeEnum);
		return entity;
	}
	@RequestMapping("/register")
	public ReturnJsonEntity register(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum codeEnum = StatusCodeEnum.CODE100000;
		String mobileNo = getParam("mobileNo");
		String nickname = getParam("nickname");
		String password = getParam("userPwd");
		String verifyCode = getParam("verifyCode");
		AppUser appUser = appUserService.selectByAccount(mobileNo);
		VerifyMobileLog mobileLog = verifyMobileService.getInfoByMobile(mobileNo);
		UserGrade userGrade = userGradeService.getDefaultGrade();
		Date nowtime = DateUtils.getNow();
		if(StringUtils.isBlank(mobileNo,nickname,password,verifyCode)){
			codeEnum = StatusCodeEnum.CODE201404;
		}else if(appUser!=null){
			codeEnum = StatusCodeEnum.CODE201401;
		}else if(appUserService.checkNickname(nickname)){
			codeEnum = StatusCodeEnum.CODE201402;
		}else if(mobileLog == null || !verifyCode.equals(mobileLog.getVerifyCode())){
			codeEnum=StatusCodeEnum.CODE201403;
		}else{
			password = password.toUpperCase();
			appUser = new AppUser();
			appUser.setIsValide((short)1);
			appUser.setMobileNo(mobileNo);
			appUser.setMoney(new BigDecimal(0));
			appUser.setNickname(nickname);
			appUser.setPassword(password);
			appUser.setRegisterTime(nowtime);
			appUser.setGradeId(userGrade.getId());
			int flag = appUserService.add(appUser);
			verifyMobileService.updateInfoStatus(mobileLog);
			
			if(flag>0){
				codeEnum=StatusCodeEnum.CODE000000;
			}
		}
		entity.init(codeEnum);
		return entity;
	}
	@RequestMapping("/login")
	public ReturnJsonEntity login(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum codeEnum = StatusCodeEnum.CODE100000;
		String deviceId = getParam("deviceId");
		String mobileNo = getParam("mobileNo");
		String password = getParam("password");
		password=password.toUpperCase();
		AppUser appUser = appUserService.selectByAccount(mobileNo);
		if(appUser==null){
			codeEnum = StatusCodeEnum.CODE200401;
		}else if(!appUser.getPassword().equals(password)){
			codeEnum = StatusCodeEnum.CODE200402;
		}else if(appUser.getIsValide() == 0){
			codeEnum = StatusCodeEnum.CODE200403;
		}else{
			String publicKey= publicKeyUtil.getKey();
			String token = SecretUtil.Instance().encode(appUser.getId());
			appUser.setAuthToken(token);
			appUser.setLastLoginTime(DateUtils.getNow());
			if(!deviceId.equals(appUser.getDeviceId())){
				codeEnum = StatusCodeEnum.CODE200200;
				appUser.setDeviceId(deviceId);
			}else{
				codeEnum = StatusCodeEnum.CODE000000;
			}
			appUserService.update(appUser);
			AppUserInfo appUserInfo = appUserService.selectInfoByUserId(appUser.getId());
			appUserInfo.setPublicKey(publicKey);
			entity.setData(appUserInfo);
		}
		entity.init(codeEnum);
		return entity;
	}
	@RequestMapping("/loginout")
	public ReturnJsonEntity loginout(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum codeEnum = StatusCodeEnum.CODE100000;
		Integer userId = getTokenUserId();
		AppUser appUser = appUserService.selectById(userId);
		if(appUser!=null){
			appUser.setAuthToken("");
			appUserService.update(appUser);
		}
		Map<String,Object> map = getPublicUserInfo();
		entity.setData(map);
		codeEnum = StatusCodeEnum.CODE000000;
		entity.init(codeEnum);
		return entity;
	}
	@RequestMapping("/defaultLogin")
	public ReturnJsonEntity defaultLogin(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum codeEnum = StatusCodeEnum.CODE100000;
		String token = getParam("token");
		String deviceId = getParam("deviceId");
		String publicKey=publicKeyUtil.getKey();
		Map<String,Object> map;
		if(StringUtils.isBlank(token)){
			map =getPublicUserInfo();
			codeEnum = StatusCodeEnum.CODE200202;
		}else{
			int userId = SecretUtil.Instance().getUserId(token);
			AppUser appUser = appUserService.selectById(userId);
			if(appUser!=null && token.equals(appUser.getAuthToken()) && deviceId.equals(appUser.getDeviceId())){
				map = new HashMap<>();
				map.put("userId", userId);
				map.put("token", token);
				map.put("publicKey", publicKey);
				map.put("isGuest", 0);
				codeEnum = StatusCodeEnum.CODE000000;
			}else{
				map =getPublicUserInfo();
				codeEnum = StatusCodeEnum.CODE200202;
			}
		}
		entity.setData(map);
		entity.init(codeEnum);
		return entity;
	}
	
	private Map<String,Object> getPublicUserInfo(){
		Map<String,Object> map = new HashMap<>();
		
		String pubUserId = PropertiesCommon.getProperty("public.userId");
		Integer userId = Integer.valueOf(pubUserId);
		String token=SecretUtil.Instance().encode(userId);
		String publicKey=publicKeyUtil.getKey();
		
		map.put("userId", userId);
		map.put("token", token);
		map.put("publicKey", publicKey);
		map.put("isGuest", 1);
		return map;
	}
}
